const express = require("express")
const router = express.Router()
const articleDB = require("../../db/article")

// 获取文章列表（按status条件查询）
router.post('/list', async (req, res) => {
  let {curPage, pageSize, classify} = req.body
  let data
  if(classify){
    data = await articleDB
                  .aggregate([
                    { $match: {classify, status: 1}},   // 查询条件
                    { $sort: {date: -1}},               // 排序
                    { $skip: curPage * pageSize},       // 跳过多少条数据
                    { $limit: pageSize}
                  ])
  }else{
    data = await articleDB
                  .aggregate([
                    { $match: {status: 1}},             // 查询条件
                    { $sort: {date: -1}},               // 排序
                    { $skip: curPage * pageSize},       // 跳过多少条数据
                    { $limit: pageSize}
                  ])
  }
  
  let totalCount = 0;
  await articleDB.find({status: 1}).countDocuments((err, result)=>{
    totalCount = result
  })
  
  res.send({
    code: 0,
    msg: '成功获取文章列表',
    data:{
      totalCount,
      list: data
    }
  })
})

// 获取文章列表（后台管理用：不按status条件查询）
router.post('/adminList', async (req, res) => {
  let {curPage, pageSize, classify} = req.body
  let data
  if(classify){
    data = await articleDB
                  .aggregate([
                    { $match: {classify}},   // 查询条件
                    { $sort: {date: -1}},               // 排序
                    { $skip: curPage * pageSize},       // 跳过多少条数据
                    { $limit: pageSize}
                  ])
  }else{
    data = await articleDB
                  .aggregate([
                    { $match: {}},             // 查询条件
                    { $sort: {date: -1}},               // 排序
                    { $skip: curPage * pageSize},       // 跳过多少条数据
                    { $limit: pageSize}
                  ])
  }
  
  let totalCount = 0;
  await articleDB.find({status: 1}).countDocuments((err, result)=>{
    totalCount = result
  })

  res.send({
    code: 0,
    msg: '成功获取文章列表',
    data:{
      totalCount,
      list: data
    }
  })
})

// 按文章id数组查找
router.post('/searchIds', async (req, res) => {
  let {ids} = req.body

  let data = await articleDB.find({
    '_id':{$in:ids}
  })
  if(!data){
    return res.send({
      code: 1,
      msg: '没有找到文章'
    })
  }
  // console.log(data);
  res.send({
    code: 0,
    msg: '找到文章了',
    data
  })
})

// 按搜索字查找文章
router.post('/search', async (req, res) => {
  let {targetWord} = req.body
  if(!targetWord){
    return res.send({
      code: 2,
      msg: '数据格式不正确'
    })
  }
  let regexp = new RegExp(targetWord, 'i')
  let data = await articleDB.find(
    {$or:[
      {title:{$regex:regexp}},
      {content:{$regex:regexp}},
      {author:{$regex:regexp}}
    ]}, {status: 1})
  
  if(!data){
    return res.send({
      code: 1,
      msg: '没有找到内容'
    })
  }

  let idArr = []
  for(let item of data){
    idArr.push(item._id)
  }
  // console.log(idArr)
  res.send({
    code: 0,
    msg: '找到文章了',
    data: idArr
  })
})

// 获取单篇文章
router.post('/single', async (req, res) => {
  let {_id} = req.body
  let doc = await articleDB.findById(_id)
  if(!doc){
    return res.send({
      code: 1,
      msg: '没有文章'
    })
  }

  // 浏览量自增1
  await articleDB.findByIdAndUpdate({_id}, { $inc: { views: 1 } })

  res.send({
    code: 0,
    msg: '获取文章成功',
    data: doc
  })
})

router.post('/like', async (req, res) => {
  let {id, ip} = req.body
  
  try{
    let doc = await articleDB.findById(id)
    if(!doc){
      return res.send({
        code: 1,
        msg: '数据错误'
      })
    }

    let likes = [...doc.likes]
    let index = likes.indexOf(ip)
    // 查重
    if(index !== -1){
      likes.splice(index, 1)
    }else{
      likes.push(ip)
    }

    await articleDB.updateOne(
      { _id:id },
      { $set: { likes } }
    )
    
    return res.send({
      code: 0,
      msg: '点赞完成',
      data: likes
    })
  }catch(e){
    // console.log(e)
    res.send({
      code: 2,
      msg: e
    })
  }
})

module.exports = router